package tools;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter
{
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        /*System.out.println("过滤器开始工作了！");*/
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       /* System.out.println("过滤器拦截了！");
        System.out.println("不担心，放行");*/

        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        String requestURI = servletRequest1.getRequestURI();

        Cookie[] cookies =servletRequest1.getCookies();
        HttpSession session = servletRequest1.getSession(false);
        String name="";
        String value="";
       /* System.out.println("requestURI = " + requestURI);
        System.out.println("requestURI.endsWith(\"/Do?method=isAdminDo\") = " + requestURI.endsWith("/Do?method=isAdminDo"));*/
        String s = servletRequest1.getRequestURI() + "?" + servletRequest1.getQueryString();
        /*System.out.println("s.endsWith(\"/Do?method=isAdminDo\") = " + s.endsWith("/Do?method=isAdminDo"));
        System.out.println("s = " + s);*/
        if(requestURI.endsWith("/my.html")
                || requestURI.endsWith("/code")
                || requestURI.endsWith("/error.html")
                || s.endsWith("/Do?method=isAdminDo")){
            filterChain.doFilter(servletRequest, servletResponse);//放行
        }else
            if(session!=null
                && session.getAttribute("pass")!=null
                && session.getAttribute("pass").equals("ok")){
            filterChain.doFilter(servletRequest, servletResponse);
        }else if(cookies==null){
            HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
            servletResponse1.sendRedirect("error.html");
        }else if(cookies!=null){
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie=cookies[i];
                name=cookie.getName();
                value=cookie.getValue();
            }
            if(!name.equals("sessionID") || value.equals("")){
                HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse;
                servletResponse1.sendRedirect("error.html");
            }else{
                filterChain.doFilter(servletRequest, servletResponse);
            }

        }
    }

    @Override
    public void destroy() {

    }
}
